import { NextResponse } from 'next/server'
import { VmsCopy } from '@/types/Model'
import prisma from '@/lib/prisma'
import { getUser } from '@/lib/authUtils'

// GET all copies for a topic
export async function GET(
  request: Request,
  { params }: { params: { topic_id: string } }
): Promise<Response> {
  try {
    const { searchParams } = new URL(request.url)
    const topicId = searchParams.get('topic_id') || params.topic_id
    
    if (!topicId) {
      return NextResponse.json(
        { error: 'Topic ID is required' },
        { status: 400 }
      )
    }
    const userid = await getUser(request)
    if (!userid) {
      return NextResponse.json(
        { error: '未授权或登录信息过期，请登录' },
        { status: 401 }
      )
    }
    if (userid instanceof NextResponse) {
      return userid
    }

    const topicCopies = await prisma.vms_copy.findMany({
      where: {
        topic_id: topicId,
        user_id:userid
      },
      select: {
        id: true,
        topic_id: true,
        title: true,
        intro: true,
        status: true,
        script_num: true,
        finished_script_num: true,
        cjsj: true,
        pxh: true
      },
      orderBy: {
        pxh: 'asc'
      }
    })
    
    return NextResponse.json(topicCopies, { status: 200 })
  } catch (error) {
    return NextResponse.json(
      { error: 'Failed to fetch copies' },
      { status: 500 }
    )
  }
}

// POST create new copy
export async function POST(request: Request): Promise<Response> {
  try {
    const userid = await getUser(request)
    if (userid instanceof NextResponse) {
      return userid
    }
    if (!userid) {
      return NextResponse.json(
        { error: '未授权或登录信息过期，请登录' },
        { status: 401 }
      )
    }
    await prisma.vms_user.update({
      where: { id: userid },
      data: {
        copy_count: {
          increment: 1
        }
      }
    })
    const body = await request.json()

    // Validate required fields
    if (!body.topic_id) {
      return NextResponse.json(
        { error: 'Topic ID is required' },
        { status: 400 }
      )
    }
    if (!body.title) {
      return NextResponse.json(
        { error: 'Title is required' },
        { status: 400 }
      )
    }

    // Get the max pxh for the topic
    const maxPxhCopy = await prisma.vms_copy.findFirst({
      where: {
        topic_id: body.topic_id
      },
      orderBy: {
        pxh: 'desc'
      },
      select: {
        pxh: true
      }
    })

    const newPxh = (maxPxhCopy?.pxh || 0) + 1

    const newCopy = await prisma.vms_copy.create({
      data: {
        id: crypto.randomUUID(),
        topic_id: body.topic_id,
        title: body.title,
        intro: body.intro || '',
        status: '文案编辑中',
        script_num: 0,
        finished_script_num: 0,
        cjsj: new Date(),
        user_id:userid,
        pxh: newPxh,
        content: body.content
      }
    })

    // 统计话题下所有文案数量和已完成文案数量
    const [totalCount, finishedCount] = await Promise.all([
      prisma.vms_copy.count({
        where: { 
          topic_id: body.topic_id || undefined
        }
      }),
      prisma.vms_copy.count({
        where: { 
          topic_id: body.topic_id || undefined,
          status: '已完成'
        }
      })
    ])

    // 更新话题的文案统计信息
    await prisma.vms_topic.update({
      where: { id: body.topic_id || undefined },
      data: {
        copy_num: totalCount,
        copy_finished_num: finishedCount
      }
    })
    
    return NextResponse.json(newCopy, { status: 201 })
  } catch (error) {
    console.error('Error creating copy:', error)
    return NextResponse.json(
      { error: 'Failed to create copy' },
      { status: 500 }
    )
  }
}

// PUT update copy
export async function PUT(request: Request): Promise<Response> {
  try {
    const userid = await getUser(request)
    if (!userid) {
      return NextResponse.json(
        { error: '未授权或登录信息过期，请登录' },
        { status: 401 }
      )
    }
    if (userid instanceof NextResponse) {
      return userid
    }
    const body = await request.json()
    
    // 先查询文案所属用户
    const copy = await prisma.vms_copy.findUnique({
      where: { id: body.id }
    })
    
    if (!copy) {
      return NextResponse.json(
        { error: '未找到文案' },
        { status: 404 }
      )
    }
    
    // 检查当前用户是否有权限修改
    if (copy.user_id !== userid) {
      return NextResponse.json(
        { error: '无权修改他人文案' },
        { status: 403 }
      )
    }
    
    // Validate required fields
    if (!body.id) {
      return NextResponse.json(
        { error: 'Copy object with ID is required' },
        { status: 400 }
      )
    }

    const updatedCopy = await prisma.vms_copy.update({
      where: {
        id: body.id
      },
      data: body
    })

    
    // 统计话题下所有文案数量和已完成文案数量
    const [totalCount, finishedCount] = await Promise.all([
      prisma.vms_copy.count({
        where: { 
          topic_id: copy.topic_id || undefined
        }
      }),
      prisma.vms_copy.count({
        where: { 
          topic_id: copy.topic_id || undefined,
          status: '已完成'
        }
      })
    ])

    // 更新话题的文案统计信息
    await prisma.vms_topic.update({
      where: { id: copy.topic_id || undefined },
      data: {
        copy_num: totalCount,
        copy_finished_num: finishedCount
      }
    })
    
    return NextResponse.json(updatedCopy, { status: 200 })
  } catch (error) {
    console.error('Error updating copy:', error)
    return NextResponse.json(
      { error: 'Failed to update copy' },
      { status: 500 }
    )
  }
}
